<?php

namespace App\LeShua;

use GuzzleHttp\Client;

class LeShua
{
    private $url;

    private $notifyUrl;

    private $sendKey;

    private $notifyKey;
    public function __construct(private $merchantId)
    {
        if (env('LESHUA_TEST'))
            $this->url = "https://t-paygate.lepass.cn/cgi-bin/lepos_pay_gateway.cgi";
        else
            $this->url = "https://paygate.leshuazf.com/cgi-bin/lepos_pay_gateway.cgi";

        $this->notifyUrl = env("LESHUA_NOTIFY_URL");
        $this->sendKey = env('LESHUA_PAY_KEY');
        $this->notifyKey = env('LESHUA_NOTIFY_KEY');
    }

    public function miniPay($openid, $orderNo, $fee)
    {
        $response = $this->send([
            'service' => 'get_tdcode',
            'pay_way' => 'WXZF',
            'jspay_flag' => 3,
            'third_order_id' => $orderNo,
            'amount' => $fee,
            'appid' => env('WECHAT_MINI_PROGRAM_APPID'),
            'sub_openid' => $openid,
            'notify_url' => $this->notifyUrl,
        ]);

        $response->checkPaySuccess();

        return $response;
    }

    public function scanPay($code, $orderNo, $fee)
    {
        $response = $this->send([
            'service' => 'upload_authcode',
            'auth_code' => $code,
            'third_order_id' => $orderNo,
            'amount' => $fee,
            'notify_url' => $this->notifyUrl,
        ]);

        //业务错误
        $response->checkPaySuccess();

        return $response;
    }

    public function getOrderInfo($selfOrderNo)
    {
        $response = $this->send([
            'service' => 'query_status',
            'third_order_id' => $selfOrderNo
        ]);

        return $response;
    }

    private function send($params) : LuShuaResponse
    {
        $params = array_merge($params, [
            'sign_type' => 'MD5',
            'merchant_id' => $this->merchantId,
            'nonce_str' => $this->getNonceStr(),
        ]);

        $params = $this->getSignedParams($params);

        //Guzzle http post
        $client = new Client();
        $response = $client->request('POST', $this->url, [
            'headers' => $this->getHeader(),
            'form_params' => $params
        ]);

        $body = $response->getBody();
        $content = $body->getContents();

        $response = new LuShuaResponse($content);

        //请求错误
        if (!$response->getResSuccess())
            throw new \Exception($response->getResErrMsg());

        return $response;
    }

    private function getSignedParams($params)
    {
        //sign
        $sign = Sign::sign($params,$this->sendKey);
        $params['sign'] = $sign;

        return $params;
    }

    private function getHeader()
    {
        return [
            'Content-Type' => 'application/x-www-form-urlencoded',
        ];
    }

    private function getNonceStr()
    {
        return uniqid();
    }
}
